const jwt = require('jsonwebtoken');
const sequelize = require('../db/index');
const { isEqual } = require('lodash');


const getPageDetail = async () => {
  const getSearch = `select name,type,params,style from page_data where type = 'search'`
  const getBanner = `select data,name,type,style from page_data where type = 'banner'`
  const getNotice = `select name,type,params,style from page_data where type = 'notice'`
  const getImage = `select data,name,type,style from page_data where type = 'image'`
  const getNavbar = `select data,name,type,style from page_data where type = 'navbar'`
  const getRichtext = `select name,type,params,style from page_data where type = 'richText'`
  const getGoods = `select name,type,params,style from page_data where type = 'good'`
  const getPage = `select name,type,params,style from page_data where type = 'page'`

  const search = await sequelize.query(getSearch, { type: sequelize.QueryTypes.SELECT, raw: true, })
  const banner = await sequelize.query(getBanner, { type: sequelize.QueryTypes.SELECT, raw: true, })
  const notice = await sequelize.query(getNotice, { type: sequelize.QueryTypes.SELECT, raw: true, })
  const image = await sequelize.query(getImage, { type: sequelize.QueryTypes.SELECT, raw: true, })
  const navbar = await sequelize.query(getNavbar, { type: sequelize.QueryTypes.SELECT, raw: true, })
  const richText = await sequelize.query(getRichtext, { type: sequelize.QueryTypes.SELECT, raw: true, })
  const goods = await sequelize.query(getGoods, { type: sequelize.QueryTypes.SELECT, raw: true, })
  const page = await sequelize.query(getPage, { type: sequelize.QueryTypes.SELECT, raw: true, })

  return {
    items: [
      search[0],
      banner[0],
      notice[0],
      image[0],
      navbar[0],
      richText[0],
      goods[0]
    ],
    page: page[0]
  }
}

const checkLoginInfo = async (username, password) => {

  if (!username || !password) {
    return { status: 1, message: '用户名或密码不能为空！' }
  }

  const sql = `select * from ev_users where username = '${username}'`
  const results = await sequelize.query(sql, { type: sequelize.QueryTypes.SELECT });
  // console.log(results);
  if (results.length !== 1) return { status: 1, message: '该用户没有注册，登录失败' }

  // 判断登录密码，核心实现思路：调用 bcrypt.compareSync(用户提交的密码, 数据库中的密码) 方法比较密码是否一致
  const compareResult = isEqual(password, results[0].password)
  // 返回值是布尔值（true 一致、false 不一致）
  if (!compareResult) {
    return { status: 1, message: '密码错误！' }
  }

  const user = { ...results[0], password: '', user_pic: '' }
  const secertKey = 'dupengwei';
  const tokenStr = jwt.sign(user, secertKey, { expiresIn: '10h' });   // token 有效期为 10 个小时

  return {
    status: 0,
    message: 'Login successful',
    // 为了方便客户端使用 Token，在服务器端直接拼接上 Bearer 的前缀
    token: 'Bearer ' + tokenStr,
  }
}

const getGoodsList = async () => {
  const result = await sequelize.query(`select * from categories`, { type: sequelize.QueryTypes.SELECT });
  const list = result
  // console.log(result);
  const children = await sequelize.query(`select * from children`, { type: sequelize.QueryTypes.SELECT });
  console.log(children);
  // 选取数据数组的前七项进行遍历，当子表的 parent_id = 父表的 category_id 时，留下
  // 遍历子表数据
  children.forEach(child => {
    // 在父表数据中查找匹配的父节点
    const parent = list.find(parent => parent.category_id === child.parent_id);
    // 如果找到了匹配的父节点，则将子节点插入到父节点的children字段中
    if (parent) {
      parent.children.push(child);
    }
  });
  return list;
}

module.exports = {
  checkLoginInfo,
  getPageDetail,
  getGoodsList
}